import type { SplitOptions } from "@/services/file-splitor/models/split-option";
import FileSplitor from "@/services/file-splitor?worker";

export async function lineReader(
  file: File,
  options: SplitOptions,
  events: { reading: (block: { lines: string[]; index: number }) => void; complete?: () => void; error?: (ev: ErrorEvent) => void },
) {
  const buffer = await file.arrayBuffer();
  const splitor = new FileSplitor();

  splitor.onmessage = (ev: MessageEvent) => {
    if (ev.data === "EOF") {
      events.complete && events.complete();
      splitor.terminate();
    } else {
      events.reading(ev.data);
    }
  };

  splitor.onerror = (ev: ErrorEvent) => {
    events.error && events.error(ev);
  };

  splitor.postMessage({ buffer, options }, [buffer]);
}
